package com.d404.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;

import im.beans.GroupMessage;
import im.beans.Group_User;
import im.beans.User;
import im.notify.server.Notify;
import manager.MessageManager;
import manager.PersistentManager;

/**
 * Servlet implementation class GetGroupMessage
 */
//@WebServlet("/SendGroupMessage")
public class SendGroupMessage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SendGroupMessage() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data,Upload.class);
		
		
		Download download = new Download();
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		try{
			
			GroupMessage gm = new GroupMessage();
			gm.setFileName(upload.getFileName());
			gm.setFileURI(gm.getFileURI());
			gm.setGroupId(upload.getGroupID());
			gm.setGroupName(upload.getGroupName());
			gm.setMessage(upload.getText());
			gm.setTimestamp(upload.getTimestamp());
			gm.setType(upload.getType()+"");
			gm.setUserId(upload.getFromID());
			gm.setUserName(upload.getFromName());
			gm.setRealName(upload.getRealName());
			
			session.save(gm);
			
			
			// 群内用户
			ArrayList<String> userAccounts = new ArrayList<>();
			
			Query gUsers = session.createQuery("select u.account from Group_User as gu,User as u where gu.groupID = ? and gu.userID = u.id");
			gUsers.setParameter(0, upload.getGroupID());
			List results = gUsers.list();
			for(Object o:results)
			{
				userAccounts.add((String)o);
			}
			
			
			// 通知
			Notify.GroupMessage message = new Notify.GroupMessage();
			message.setGroupId(upload.getGroupID());
			MessageManager.sendGroupMessage(userAccounts, JSON.toJSONString(message));
			tx.commit();
			download.setStatus(Download.SUCCESS);
			
		}catch(Exception e)
		{
			tx.rollback();
			download.setStatus(Download.FAILD);
			e.printStackTrace();
		}finally {
//			session.close();
		}
		
		System.out.println(JSON.toJSONString(download));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(JSON.toJSONString(download));
	}
	
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	// 上行数据
    public static class Upload {
        public static final int FROMLOCAL = 1;
        public static final int FROMREMOTE = 2;

        long fromID;
        long GroupID;
        String fromName;
        String GroupName;
        String realName;
        long type;
        String fileURI;
        String fileName;
        String text;
        long timestamp;

        public Upload() {
        }

        public Upload(long fromID, long groupID, String fromName, String groupName, long type, String fileURI, String fileName, String text, long timestamp,String realName) {
            this.fromID = fromID;
            GroupID = groupID;
            this.fromName = fromName;
            GroupName = groupName;
            this.type = type;
            this.fileURI = fileURI;
            this.fileName = fileName;
            this.text = text;
            this.timestamp = timestamp;
            this.realName = realName;
        }

        public long getFromID() {
            return fromID;
        }

        public void setFromID(long fromID) {
            this.fromID = fromID;
        }

        public long getGroupID() {
            return GroupID;
        }

        public void setGroupID(long groupID) {
            GroupID = groupID;
        }

        public String getFromName() {
            return fromName;
        }

        public void setFromName(String fromName) {
            this.fromName = fromName;
        }

        public String getGroupName() {
            return GroupName;
        }

        public void setGroupName(String groupName) {
            GroupName = groupName;
        }

        public long getType() {
            return type;
        }

        public void setType(long type) {
            this.type = type;
        }

        public String getFileURI() {
            return fileURI;
        }

        public void setFileURI(String fileURI) {
            this.fileURI = fileURI;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(long timestamp) {
            this.timestamp = timestamp;
        }

        public String getRealName() {
            return realName;
        }

        public void setRealName(String realName) {
            this.realName = realName;
        }
    }
    
    // 下行数据
    public static class Download
    {
        public static int SUCCESS = 1;
        public static int FAILD = 2;
        int status;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }
    }

}
